package priv.winnine.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import priv.winnine.entity.bo.Constant;
import priv.winnine.entity.bo.RequestInfo;
import priv.winnine.entity.bo.RequestRecord;
import priv.winnine.entity.vo.Response;

@Slf4j
@ControllerAdvice
public class ApiResponseBodyHandler implements ResponseBodyAdvice<Response> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Response beforeBodyWrite(Response response, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) serverHttpRequest;
        response.addData((String) servletServerHttpRequest.getServletRequest().getAttribute(Constant.HTTP_HEADER_DATA));
        if (log.isDebugEnabled()) {
            log.info("response-bean = {}", response);
        }
        RequestRecord requestRecord = RequestRecord.builder()
                .requestInfo((RequestInfo) servletServerHttpRequest.getServletRequest().getAttribute(Constant.HTTP_REQUEST_INFO))
                .request((String) servletServerHttpRequest.getServletRequest().getAttribute(Constant.HTTP_REQUEST_STRING))
                .response(response)
                .build();
        doRecord(requestRecord);
        return response;
    }

    /**
     * 做响应的记录
     * @param requestRecord
     */
    private void doRecord(RequestRecord requestRecord) {
        if (requestRecord.getResponse().ifSuccess()) {
            log.info("requestRecord = {}", requestRecord);
            // TODO 做一些记录
        } else {
            log.error("requestRecord = {}", requestRecord);
            // TODO 做一些记录
        }
    }
}
